package com.dao;
import java.util.List;
import com.beans.GoodsInfo;
import com.jdbc.DBUtil;
import com.utils.PageInfo;
import com.utils.StrUtil;

//商品操作相关
public class GoodsDao {
	
	//删除商品信息
	public int delGoodsById(int id){
		String sql="delete from goodsInfo where id=?";
		return DBUtil.update(sql, id);
	}
	//根据商品id查询商品信息
	public GoodsInfo getGoodsById(int goodsId){
		String sql="select * from goodsInfo where id=?" ;
		return DBUtil.getOneObject(sql, GoodsInfo.class, goodsId);
	}
	
	//更改商品信息
	public int updateGoods(GoodsInfo goods){
		String sql="update goodsInfo  set goodsName=? ,unit=? ,price=?,des=?,producter=?,bigCateId=?, smallCateId=? ,pictureData=? where id=?";
		Object [] params={
				goods.getGoodsName(),
				goods.getUnit(),
				goods.getPrice(),
				goods.getDes(),
				goods.getProducter(),
				goods.getBigCateId(),
				goods.getSmallCateId(),
				goods.getPictureData(),
				goods.getId()
		};
		
		return DBUtil.update(sql, params);
	}
	 
	//多条件分页查询商品列表
	public List<GoodsInfo> getGoodsList(int bigCateId, int smallCateId, String goodsName,PageInfo pageInfo) {
		String sql= " select temp.*,b.cateName as smallCateName from "
				+ "(select a.*,b.cateName as bigCateName from goodsInfo a left join cateInfo b on a.bigcateId=b.id) temp "
				+ " left join cateInfo b on temp.smallcateId=b.id  where 1=1 " ; 
		  
		if(bigCateId!=0){
			sql+=" and bigCateId="+bigCateId;
		}
	
		if(bigCateId!=0){
			sql+=" and smallCateId="+smallCateId;
		}
		
		if(!StrUtil.isNullOrEmpty(goodsName)){
			sql+=" and goodsName like '%"+goodsName+"%'";
		}
		
		sql+=" order by editDate desc limit ?,?";
		
		return DBUtil.getList(sql, GoodsInfo.class, pageInfo.getBeginRow(),pageInfo.getPageSize());	
	}
	
	//查询商品总数(用于分页)
	public int getGoodsCount(int bigCateId,int smallCateId,String goodsName){
		String sql= "select count(*) from goodsInfo where 1=1 " ;
		
		if(bigCateId!=0){
			sql+=" and bigCateId="+bigCateId;
		}
	
		if(bigCateId!=0){
			sql+=" and smallCateId="+smallCateId;
		}
		
		if(!StrUtil.isNullOrEmpty(goodsName)){
			sql+=" and goodsName like '%"+goodsName+"%'";
		}
		
		return new Integer(DBUtil.getScalar(sql)+"");
	}
	
	//添加商品,返回值为新增加的商品的id
	public int addGoods(GoodsInfo goods) {
		String sql="insert into goodsInfo (goodsName,bigCateId,smallCateId,unit,price,producter,des,pictureData)  values (?,?,?,?,?,?,?,?)";
		Object [] params={
				goods.getGoodsName(),
				goods.getBigCateId(),
				goods.getSmallCateId(),
				goods.getUnit(),
				goods.getPrice(),
				goods.getProducter(),
				goods.getDes(),	
				goods.getPictureData()
		};
		
		return DBUtil.getAddAndById(sql, params);
	}
	

}

